package com.lill.system.web;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.lill.common.component.util.PageUtils;
import com.lill.common.component.util.Query;
import com.lill.common.component.util.R;
import com.lill.org.model.EmployeeModel;
import com.lill.org.service.IEmployeeService;
import com.lill.support.annotation.CurrentUser;
import com.lill.system.constant.SystemConstant;
import com.lill.system.model.SysUserEntity;
import com.lill.system.service.ICommonRedisService;
import com.lill.system.service.ISysUserRoleService;
import com.lill.system.service.ISysUserService;

/**
 * 系统用户
 *
 * @author lill
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
	private ICommonRedisService commonRedisService;

    /**
     * 所有用户列表 
     */
    @RequestMapping("/list")
//    @RequiresPermissions("sys:user:list")
    public R list(@CurrentUser SysUserEntity user,@RequestParam Map<String, Object> params) {
        //只有超级管理员，才能查看所有管理员列表
        if (!SystemConstant.SUPER_ADMIN.equals(user.getId())) {
            params.put("companyId", user.getCompanyId());
        }

        //查询列表数据
        Query query = new Query(params);
        List<SysUserEntity> userList = sysUserService.queryList(query);
        int total = sysUserService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(userList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 获取登录的用户信息
     */
    @RequestMapping("/info")
    public R info(@CurrentUser SysUserEntity user) {
        return R.ok().put("user", user);
    }

    /**
     * 修改登录用户密码
     */
    @RequestMapping("/password")
    public R password(@CurrentUser SysUserEntity user,String password, String newPassword) {
//        Assert.isBlank(newPassword, "新密码不为能空");

        //sha256加密
        password = new Sha256Hash(password).toHex();
        //sha256加密
        newPassword = new Sha256Hash(newPassword).toHex();

        if (password.equals(newPassword)) {
            return R.error("密码不能与原密码相同");
        }

        //更新密码
        int count = sysUserService.updatePassword(user.getId(), password, newPassword);
        if (count == 0) {
            return R.error("原密码不正确");
        }
        //退出
//        ShiroUtils.logout();

        return R.ok("密码修改成功");
    }
    
    /**
     * 修改登录用户密码
     */
//    @RequiresPermissions("sys:user:initpassword")
    @RequestMapping("/initpassword")
    public R initpassword(@CurrentUser SysUserEntity user,@RequestParam(required=true) String id) {
    	//sha256加密
    	String newPassword = new Sha256Hash(SystemConstant.DEFAULT_OLD_PASS_WORD).toHex();
    	
    	//更新密码
    	int count = sysUserService.initPassword(id, newPassword);
    	if (count == 0) {
    		return R.error("密码修改失败");
    	}
    	return R.ok("密码修改成功");
    }

    /**
     * 用户信息
     */
    @RequestMapping("/info/{id}")
//    @RequiresPermissions("sys:user:info")
    public R info(@PathVariable("id") String id) {
        SysUserEntity user = sysUserService.queryObject(id);

        //获取用户所属的角色列表
        List<String> roleIdList = sysUserRoleService.queryRoleIdList(id);
        if(null!=roleIdList&&!roleIdList.isEmpty()){
        	user.setRoleIdList(roleIdList);
        }
        
        List<EmployeeModel> employeeList=null;
        if(StringUtils.isNotEmpty(user.getPersonId())){
        	Map<String, Object> mapParams=new HashMap<String, Object>();
        	mapParams.put("personId", user.getPersonId());
        	employeeList=employeeService.queryList(mapParams);
        }
        
        return R.ok().put("user", user).put("employeeList", employeeList);
    }

    /**
     * 保存用户
     */
    @RequestMapping("/save")
//    @RequiresPermissions("sys:user:save")
    public R save(@CurrentUser SysUserEntity curUser,@RequestBody SysUserEntity user) {
//        ValidatorUtils.validateEntity(user, AddGroup.class);
    	user.setCreateTime(new Date());
    	user.setStatus(1);
        user.setCreateUser(curUser.getId());
        
        Map<String, Object> params=new HashMap<String, Object>();
    	params.put("userName", user.getUserName());
//    	int phoneCount=sysUserService.queryTotal(params);
//    	if(phoneCount>0){
//    		return R.error(1,"该手机号已经使用！");
//    	}
        
        int result=sysUserService.save(user);
        if(result>0){
    		return R.ok();
        }else{
        	return R.failure();
        }
    }

    /**
     * 修改用户
     */
    @RequestMapping("/update")
//    @RequiresPermissions("sys:user:update")
    public R update(@CurrentUser SysUserEntity curUser,@RequestBody SysUserEntity user) {
//        ValidatorUtils.validateEntity(user, UpdateGroup.class);

        user.setUpdateUser(curUser.getId());
        user.setUpdateTime(new Date());
        
        Map<String, Object> params=new HashMap<String, Object>();
    	params.put("userName", user.getUserName());
    	int phoneCount=sysUserService.queryTotal(params);
    	if(phoneCount>1){
    		return R.error(1,"该手机号已经使用！");
    	}
        
        int result=sysUserService.update(user,curUser);
        if(result>0){
    		return R.ok();
        }else{
        	return R.failure();
        }
    }

    /**
     * 删除用户
     */
    @RequestMapping("/delete")
//    @RequiresPermissions("sys:user:delete")
    public R delete(@CurrentUser SysUserEntity curUser,@RequestBody String[] ids) {
        if (ArrayUtils.contains(ids, 1L)) {
            return R.error("系统管理员不能删除");
        }
        if (ArrayUtils.contains(ids, curUser.getId())) {
            return R.error("当前用户不能删除");
        }
        Map<String, Object> params=new HashMap<String, Object>();
    	params.put("ids", ids);
    	params.put("updateUser", curUser.getId());
    	params.put("updateTime", new Date());
        
    	int result=sysUserService.deleteLogicByMap(params);
    	if(result>0){
    		return R.ok();
        }else{
        	return R.failure();
        }
    }
    
    @RequestMapping("/deleteToken")
    public R deleteAppToken(@RequestParam(required=false) String authToken) {
    	commonRedisService.deleteAppTokens(authToken);
    	return R.ok();
    }
}
